<script setup lang="ts">
import { object, string, type InferType } from 'yup'
import type { FormSubmitEvent } from '#ui/types'

const schema = object({
  email: string().email('Invalid email').required('Required'),
  password: string()
    .min(6, 'Must be at least 6 characters')
    .required('Required'),
})

type Schema = InferType<typeof schema>

const state = reactive({
  email: undefined,
  password: undefined,
})

const { login } = useLogin()
const toast = useToast()
const directus = useDirectus()
const route = useRoute()
let redirect = route.query.redirect as string
if (!redirect) redirect = '/'
const { public: { directusUrl, redirectUrl } } = useRuntimeConfig()
const ssoRedirect = encodeURIComponent(`${redirectUrl}/login-sso?redirect=${redirect}`)
const ssoLink = `${directusUrl}/auth/login/microsoft?redirect=${ssoRedirect}`

const loading = ref(false)

async function onSubmit(event: FormSubmitEvent<Schema>) {
  loading.value = true
  const { email, password } = event.data

  try {
    await directus.login(email, password)
    login.value.isLoggedIn = true
    await navigateTo(redirect, { replace: true })
  }
  catch (error) {
    toast.add({
      title: 'Login Error',
      description: directusErrorMessage(error),
      color: 'red',
    })
  }
  loading.value = false
}
</script>

<template>
  <UContainer class="flex max-w-xs lg:px-6 h-[calc(100vh-10rem)]">
    <UForm :schema="schema" :state="state" class="w-full my-auto space-y-4" @submit="onSubmit">
      <MySection>Login to proceed</MySection>
      <UFormGroup label="Email" name="email">
        <UInput v-model="state.email" autocomplete="on" />
      </UFormGroup>
      <UFormGroup label="Password" name="password">
        <UInput v-model="state.password" type="password" autocomplete="on" />
      </UFormGroup>
      <div class="flex justify-between items-center">
        <UButton type="submit" :loading="loading">
          Sign in
        </UButton>
        <span class="text-sm text-gray-500">/</span>
        <UButton :to="ssoLink" icon="i-bxl-microsoft" variant="outline">
          Sign in with Microsoft
        </UButton>
      </div>
      <div class="flex justify-between">
        <ULink to="/register" class="hover:underline text-sm text-primary">
          Create account
        </ULink>
        <ULink to="/reset-password" class="hover:underline text-sm text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200">
          Forget password?
        </ULink>
      </div>
    </UForm>
  </UContainer>
</template>
